package com.playball.lottery.frm.buyhall;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.customview.BallDTO;
import com.playball.lottery.customview.MyDialog;
import com.playball.lottery.customview.NewDelButtonAdapter;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.yhzx.BetProtocolActivity;
import com.playball.lottery.frm.yhzx.JddRechargeListActivity;
import com.playball.lottery.frm.yhzx.LoginActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.DynArrayInt;
import com.playball.lottery.util.GetIDAsyncLoader;
import com.playball.lottery.util.LotConstants;
import com.playball.lottery.util.MyPreference;
import com.playball.lottery.util.PreferencesUtils;
import com.playball.lottery.util.SysApplication;


/**
 * 双色球选号列表
 * 
 * @author Administrator
 * 
 */
public class SsqxhlbActivity extends ListActivity implements DefConstants {
	LinearLayout buy_ssqxhlb_ll01;
	LinearLayout buy_ssqxhlb_ll02;
	LinearLayout buy_ssqxhlb_ll03;
	Button buy_ssqxhlb_Button06;
	/** 发起合买 */
	Button buy_ssqxhlb_btn_hemai;
	EditText buy_ssqxhlb_EditText1;
	TextView buy_ssqxhlb_TextView03;
	EditText zhuihao_EditText;
	View buy_ssqxhlb_linearlayout01;
	View buy_ssqxhlb_linearlayout02;

	private DynArrayInt red_dintInt;
	private DynArrayInt blue_dintInt;
	private DynArrayInt money_dintInt;
	private int playTypeId = 502;
	private int allMoney;
	private int lotID;
	// private String vouchersNo = "";// 折扣编号
	// private double canDeductMoney;// 折扣金额
	private String issueID;
	private String issueName;
	private int buy_icon;
	private ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
	private int bs = 1;
	private int zh = 1; // 追号
	LinearLayout foot_layout;
	TextView tv_bet_protocol;
	CheckBox cb_bet_protocol;

	private String[] dyn;

	private LinearLayout yincangyu1, yincangyu2;
	private CheckBox iszhuihao;
	private TextView wuqi, shiqi, shiwuqi;
	private LinearLayout ceshi;

	private Context context;
	private PreferencesUtils pUtil;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Bundle b = msg.getData();
			issueID = b.getString("issueID");
			issueName = b.getString("issueName");

		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.buy_ssqxhlb);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
						| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		SysApplication.getInstance().addActivity(this);
		context = this;
		pUtil = new PreferencesUtils(context, Constants.PREFERENCES_NAME);
		initViewChange();
	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	/**
	 * 初始化 判断是不是 幸运装盘过来的
	 */
	private void initViewChange() {

		// app_ssqdto = (ApplicationBall) getApplication();
		// 初始化按钮

		initView();

		buy_ssqxhlb_EditText1 = (EditText) findViewById(R.id.buy_ssqxhlb_EditText01);
		// 倍数的焦点事件
		buy_ssqxhlb_EditText1.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					yincangyu1 = (LinearLayout) findViewById(R.id.yincangyu1);
					yincangyu1.setVisibility(View.GONE);
					yincangyu2 = (LinearLayout) findViewById(R.id.yicangyu2);
					yincangyu2.setVisibility(View.GONE);
				}

			}
		});
		buy_ssqxhlb_EditText1.addTextChangedListener(textWatcher);
		zhuihao_EditText = (EditText) findViewById(R.id.buy_ssqxhlb_zhuihao);
		/*
		 * 追号的焦点事件
		 */
		zhuihao_EditText.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					yincangyu2 = (LinearLayout) findViewById(R.id.yicangyu2);
					yincangyu2.setVisibility(View.VISIBLE);
					wuqi = (TextView) findViewById(R.id.wuqi);
					shiqi = (TextView) findViewById(R.id.shiqi);
					shiwuqi = (TextView) findViewById(R.id.shiwuqi);
					if (zh > 1) {
						yincangyu1.setVisibility(View.VISIBLE);
					}
					wuqi.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							zh = 5;
							zhuihao_EditText.setText("5");
						}
					});
					shiqi.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							zh = 10;
							zhuihao_EditText.setText("10");
						}
					});
					shiwuqi.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							zh = 15;
							zhuihao_EditText.setText("15");
						}
					});
				} else {
					yincangyu2.setVisibility(View.GONE);
					if (yincangyu1.VISIBLE == View.VISIBLE) {
						yincangyu1.setVisibility(View.GONE);
					}

				}

			}
		});
		zhuihao_EditText.addTextChangedListener(zhuihaoWatcher);

		LayoutInflater inflater = LayoutInflater.from(this);
		foot_layout = (LinearLayout) inflater.inflate(R.layout.bet_protocol_foot, null);
		tv_bet_protocol = (TextView) foot_layout.findViewById(R.id.bet_protocol);
		cb_bet_protocol = (CheckBox) foot_layout.findViewById(R.id.bet_protocol_choice);
		tv_bet_protocol.setText(Html.fromHtml("<u>我已满18周岁并同意《服务条款》"));// "<u>我已阅读并同意《代购合买协议》"
		cb_bet_protocol.setChecked(true);
		tv_bet_protocol.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivityForResult(new Intent(SsqxhlbActivity.this, BetProtocolActivity.class), 0);
				// Log.v("ssqxhlb", "代购合买协议");
			}
		});
		this.getListView().addFooterView(foot_layout);

		// 获得传来的数组，并放入ListView
		Intent intent = getIntent();
		allMoney = intent.getIntExtra("AllMoney", 0);
		issueID = intent.getStringExtra("IssueID");// 可以不要
		issueName = intent.getStringExtra("IssueName");// -1 最新的
		lotID = intent.getIntExtra("LotID", LOT_ID_SSQ);
		if (issueID == null || issueName == null) {
			GetIDAsyncLoader task = new GetIDAsyncLoader(this, handler, lotID);
			String[] parms = new String[2];
			parms[0] = "200";
			JSONObject jsob = new JSONObject();
			try {
				// 设置请求所需参数
				jsob.put("LottID", lotID);
			} catch (JSONException ex) {
				// TODO Auto-generated catch block
				Log.e("error", ex.toString());
			}
			parms[1] = jsob.toString();
			task.execute(parms);
		}
		buy_ssqxhlb_TextView03.setText(allMoney + "");
		@SuppressWarnings("unchecked")
		ArrayList<BallDTO> arrayList = (ArrayList<BallDTO>) intent.getSerializableExtra("list_ssqdto");
		for (BallDTO ssqdto : arrayList) {
			String ssq_ball = ssqdto.getSsq_ball();
			list = getData(ssq_ball);
		}
		InitBaseAdapter(list);

		// 继续添加号码
		buy_ssqxhlb_ll01.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra("ifbacklist", true);
				intent.setClass(context, SsqxhActivity.class);
				startActivity(intent);
				finish();
			}
		});

		// 随机添加号码
		buy_ssqxhlb_ll02.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				buy_ssqxhlb_linearlayout01.setVisibility(View.VISIBLE);
				buy_ssqxhlb_linearlayout02.setVisibility(View.GONE);

				// 随机6个红球和1个蓝球
				int red_random[] = RandomGenData(1, 33, 6, "red");
				int blue_random[] = RandomGenData(1, 16, 1, "blue");
				// 随机生成的号码添加到dintInt
				red_dintInt = new DynArrayInt();
				blue_dintInt = new DynArrayInt();
				red_dintInt.addInt(red_random);
				blue_dintInt.addInt(blue_random);

				// 在这个Activity每选中一注球，所有号码全部存储到xxx_dintInt int[]数组中
				String red_ball = red_dintInt.getAllIntToString(red_dintInt.getAllInt());
				red_ball = red_ball.substring(0, red_ball.length() - 1);
				String blue_ball = blue_dintInt.getAllIntToString(blue_dintInt.getAllInt());
				blue_ball = blue_ball.substring(0, blue_ball.length() - 1);
				// 实例化一个新的BallDTO放入到全局变量ApplicationBall中的List_ssq里
				BallDTO ssqdto = new BallDTO();
				ssqdto.setSsq_ball(red_ball + "-" + blue_ball + "-" + 2);
				// 获得自定义的应用程序BallDTO

				// 将我们放到进程中的全局变量拿出来，看是不是我们曾经设置的值
				Log.i("application_ssq", "InitLabel:application_ssq_sel:"
						+ ApplicationData.getInstance().getList_ssqdto().size());
				// 新选的号码，追加在ApplicationBall全局变量list_ssqdto里
				ApplicationData.getInstance().getList_ssqdto().add(ssqdto);
				allMoney += 2;
				ApplicationData.getInstance().setAll_ssqmoney(allMoney);
				InitBaseAdapter(getData(red_ball + "-" + blue_ball + "-" + 2));
			}
		});

		// 清空
		buy_ssqxhlb_ll03.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (ApplicationData.getInstance().getList_ssqdto().size() > 0) {
					MyDialog.Builder dialog = new MyDialog.Builder(SsqxhlbActivity.this);
					dialog.setTitle("清空号码提示");
					dialog.setMessage("清空后您已选择的号码列表将会清空，确认继续?");
					dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
							buy_ssqxhlb_EditText1.setText("1");
							// buy_ssqxhlb_TextView01.setText("0");
							// buy_ssqxhlb_TextView02.setText("1");
							zhuihao_EditText.setText("1");
							allMoney = 0;
							bs = 1;
							zh = 1;
							buy_ssqxhlb_TextView03.setText("0");
							// 获得自定义的应用程序BallDTO,初始化
							ApplicationData.getInstance().initList();
							list = new ArrayList<HashMap<String, Object>>();
							buy_ssqxhlb_linearlayout01.setVisibility(View.GONE);
							buy_ssqxhlb_linearlayout02.setVisibility(View.VISIBLE);
						}
					});
					dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					}).create().show();

				}
			}
		});

		// 购买
		buy_ssqxhlb_Button06.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (ApplicationData.getInstance().isUserLogin()) {
					if (issueID == null || issueName == null) {
						Toast.makeText(context, R.string.the_network_is_not_to_force, Toast.LENGTH_SHORT).show();
						return;
					}
					if(bs * allMoney > 2000000){
						Toast.makeText(context, "单个方案的总金额必须在2彩豆至2000000彩豆之间", Toast.LENGTH_SHORT).show();
						return;
					}
					// bs =
					// Integer.parseInt(buy_ssqxhlb_EditText1.getText().toString());
					if (list.size() < 1) {
						Toast.makeText(SsqxhlbActivity.this, R.string.betting_number_cannot_be_empty,
								Toast.LENGTH_SHORT).show();
					} /*
					 * else if
					 * (buy_ssqxhlb_EditText1.getText().toString().equals("")) {
					 * buy_ssqxhlb_EditText1.setText("1");
					 * Toast.makeText(SsqxhlbActivity.this,
					 * R.string.buy_at_least_one_times, Toast.LENGTH_SHORT)
					 * .show(); } else if
					 * (zhuihao_EditText.getText().toString().equals("")) {
					 * zhuihao_EditText.setText("1");
					 * Toast.makeText(SsqxhlbActivity.this,
					 * R.string.period_of_time_can_not_be_empty,
					 * Toast.LENGTH_SHORT).show(); }
					 */else {

						if (cb_bet_protocol.isChecked() == false) {
							Toast.makeText(SsqxhlbActivity.this, R.string.need_to_agree_to_just_can_continue_to_buy,
									Toast.LENGTH_SHORT).show();
							return;
						}

						if (zh == 1) {
							startBuyThread();
						} else {
							startZhuiHaoThread();
						}
					}
				} else {
					Intent intent = new Intent();
					intent.setClass(context, LoginActivity.class);
					startActivity(intent);
				}
			}
		});

		// 发起合买
		buy_ssqxhlb_btn_hemai.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (ApplicationData.getInstance().isUserLogin()) {
					if (issueID == null || issueName == null) {
						Toast.makeText(SsqxhlbActivity.this, R.string.the_network_is_not_to_force, Toast.LENGTH_SHORT)
								.show();
						return;
					}
					// bs =
					// Integer.parseInt(buy_ssqxhlb_EditText1.getText().toString());
					if (list.size() < 1) {
						Toast.makeText(SsqxhlbActivity.this, R.string.betting_number_cannot_be_empty,
								Toast.LENGTH_SHORT).show();
					} /*
					 * else if
					 * (buy_ssqxhlb_EditText1.getText().toString().equals("") ||
					 * Long
					 * .parseLong(buy_ssqxhlb_EditText1.getText().toString()) ==
					 * 0) { buy_ssqxhlb_EditText1.setText("1");
					 * Toast.makeText(SsqxhlbActivity.this,
					 * R.string.buy_at_least_one_times, Toast.LENGTH_SHORT)
					 * .show(); } else if
					 * (zhuihao_EditText.getText().toString().equals("")) {
					 * zhuihao_EditText.setText("1");
					 * Toast.makeText(SsqxhlbActivity.this,
					 * R.string.period_of_time_can_not_be_empty,
					 * Toast.LENGTH_SHORT).show(); }
					 */else {

						if (cb_bet_protocol.isChecked() == false) {
							Toast.makeText(SsqxhlbActivity.this, R.string.need_to_agree_to_just_can_continue_to_buy,
									Toast.LENGTH_SHORT).show();
							return;
						}

						Intent intent = new Intent();
						intent.putExtra("list_ssqdto", ApplicationData.getInstance().getList_ssqdto());
						intent.putExtra("AllMoney", ApplicationData.getInstance().getAll_ssqmoney());
						intent.putExtra("bs", bs);
						intent.putExtra("LotID", lotID);
						intent.putExtra("IssueID", issueID);
						intent.putExtra("IssueName", issueName);
						intent.putExtra("PlayTypeId", playTypeId);
						intent.setClass(SsqxhlbActivity.this, FaQiHeMaiActivity.class);
						SsqxhlbActivity.this.startActivityForResult(intent, REQ_CODE_BUYMAIN);
					}
				} else {
					Intent intent = new Intent();
					intent.setClass(context, LoginActivity.class);
					startActivity(intent);
				}
			}
		});

	}

	// 追号的EditText监听
	private TextWatcher zhuihaoWatcher = new TextWatcher() {
		private boolean isChanged = false;

		@Override
		public void afterTextChanged(Editable s) {
			if (isChanged) {
				return;
			}
			if (!zhuihao_EditText.getText().toString().equals("")) {
				zh = Integer.parseInt(s.toString());
				isChanged = true;
				String str2 = s.toString().trim().replaceFirst("^0*", "");// 正则去除
				if (zh < 1) {
					// Toast.makeText(SsqxhlbActivity.this,
					// R.string.buy_at_least_one, Toast.LENGTH_SHORT).show();
					zhuihao_EditText.setText("1");
					zh = 1;
				} else if (zh > 50) {
					Toast.makeText(SsqxhlbActivity.this, R.string.after_fifty_most_period, Toast.LENGTH_SHORT).show();
					zhuihao_EditText.setText("50");
					zh = 50;
				} else {
					yincangyu1 = (LinearLayout) findViewById(R.id.yincangyu1);
					if (zh == 1) {
						yincangyu1.setVisibility(View.GONE);
					} else {
						yincangyu1.setVisibility(View.VISIBLE);
					}
					zhuihao_EditText.setText(str2);
				}
				zhuihao_EditText.setSelection(zhuihao_EditText.length());
				isChanged = false;
				zhuihao_EditText.invalidate();
			} else {
				zh = 1;
			}
			if (zh == 1) {
				buy_ssqxhlb_btn_hemai.setEnabled(true);
				buy_ssqxhlb_btn_hemai.setBackgroundResource(R.drawable.ui_new_btn_yes_selector);
			} else {
				buy_ssqxhlb_btn_hemai.setEnabled(false);
				buy_ssqxhlb_btn_hemai.setBackgroundResource(R.drawable.ui_new_btn_cancel_normal);
			}
			buy_ssqxhlb_TextView03.setText(allMoney * zh * bs + "");
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

	};

	// 倍数的EditText监听
	private TextWatcher textWatcher = new TextWatcher() {
		private boolean isChanged = false;

		@Override
		public void afterTextChanged(Editable s) {
			if (isChanged) {
				return;
			}
			if (!buy_ssqxhlb_EditText1.getText().toString().equals("")) {
				bs = Integer.parseInt(s.toString());
				isChanged = true;
				String str2 = s.toString().trim().replaceFirst("^0*", "");// 正则去除
				if (bs < 1) {
					buy_ssqxhlb_EditText1.setText("1");
					bs = 1;
				} else if (bs > 999) {
					Toast.makeText(SsqxhlbActivity.this, R.string.the_maximum_ratio_of_dig_3_nine,
							Toast.LENGTH_SHORT).show();
					buy_ssqxhlb_EditText1.setText("999");
					bs = 999;
				} else {
					buy_ssqxhlb_EditText1.setText(str2);
				}
				buy_ssqxhlb_EditText1.setSelection(buy_ssqxhlb_EditText1.length());
				isChanged = false;
				buy_ssqxhlb_EditText1.invalidate();
			} else {
				bs = 1;
			}
			buy_ssqxhlb_TextView03.setText(allMoney * zh * bs + "");
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

	};

	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		String action;

		ShowTipDialog showdialog = new ShowTipDialog();

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(SsqxhlbActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;

			action = paramsArr[1];
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(paramsArr[0], UserID, action, getApplicationContext());
			// 获取请求返回值

			// System.out.println("strResult = " + strResult);
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				if (action.equals("207")) {
					Buy(result);
				} else {
					Buy2(result);
				}
				showdialog.closeDialog();
			} else {
				Toast.makeText(SsqxhlbActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	/**
	 * 拼接投注号码
	 * 
	 * @return
	 */
	public List<Map<String, Object>> getLotNum() {
		List<BallDTO> arrayList = ApplicationData.getInstance().getList_ssqdto();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (BallDTO elvdto : arrayList) {
			String ssq_ball = elvdto.getSsq_ball();
			ssq_ball = ssq_ball.replace("-", " + ");
			ssq_ball = ssq_ball.substring(0, ssq_ball.lastIndexOf("+"));
			ssq_ball = ssq_ball.replace(",", " ");
			// Log.v("getLotNum1ss", "ssq_ball= "+ssq_ball.toString());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("number", ssq_ball);

			if ((ssq_ball.split("\\+")[0]).length() > 18 || ((ssq_ball.split("\\+")[1]).length() > 4)) {
				map.put("playid", SSQ_ZX_F);// "07 11 12 15 26 30 33 + 05"或"07 11 12 15 26 30 + 05 08"
			} else {
				map.put("playid", SSQ_ZX_D);// 单式
			}
			list.add(map);
		}
		Log.v("getLotNum", "list= " + list.toString());
		return list;
	}

	// 追号线程
	private void startZhuiHaoThread() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list = getLotNum();    

		AsyncLoader task = new AsyncLoader();
		dyn = new String[2];
		JSONObject params = new JSONObject();
		try {
			JSONArray array1 = new JSONArray();// 彩票
			for (int i = 0; i < list.size(); i++) {
				JSONObject o = new JSONObject(list.get(i));
				array1.put(o);
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("LotteryNumber", array1);
			
			params.put("LottID", lotID);
			params.put("StopMoney", iszhuihao.isChecked() ? 1 : 0);
			params.put("ChaseCount", zh);
			params.put("IssueID", issueID);
			params.put("Money", bs * allMoney);
			params.put("Multiple", bs);
			params.put("BuyMoney", bs * allMoney * zh);
			params.put("ChaseIsuses", jsonObject);
		} catch (JSONException ex) {
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		dyn[1] = "2082";
		task.execute(dyn);
	}

	private void startBuyThread() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list = getLotNum();

		AsyncLoader task = new AsyncLoader();
		dyn = new String[2];
		JSONObject params = new JSONObject();
		try {
			// 设置请求所需参数
			JSONArray array1 = new JSONArray();
			for (int i = 0; i < list.size(); i++) {
				JSONObject o = new JSONObject(list.get(i));
				// System.out.println(o);
				array1.put(o);
			}
			// Log.v("maina", "array1= "+array1.toString());
			params.put("SchemeType", 1);// 方案类型 1自购，2合买，3保存 1
			params.put("BetType", 1);// 投注类型 1选号投注 2单式上传 3先发后传 1
			params.put("BonusScale", 0);
			params.put("AssureShare", 0);
			params.put("Description", "");
			params.put("OpenUserList", "");
			params.put("SecrecyLevel", 4);
			params.put("BuyShare", bs * allMoney);
			params.put("Multiple", bs);
			params.put("LotteryID", lotID);
			 params.put("IssueID", issueID);
			params.put("IssueName", issueName);
			params.put("Number", array1);
			params.put("Money", bs * allMoney);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		dyn[1] = "207";// 200
		task.execute(dyn);
	}

	public void Buy(String strResult) {

		// System.out.println("BUY====strResult:" + strResult);

		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			if (Integer.parseInt(js.getString("Code")) < 0) {
				buy_icon = R.drawable.buy_failure;
				String balanceNotFull = js.getString("Data");
				// String balance = "当前余额:"+
				// ApplicationData.getInstance().getUserMoney() +"彩豆" +"\n";
				if(js.getString("Data").contains(Constants.BALANCE_BUZU)) {
					Intent intent = new Intent();
					intent.setClass(context, JddRechargeListActivity.class);
					intent.putExtra("params", dyn[0]);
					startActivityForResult(intent, REQ_CODE_NO_MONEY_2_RECHARGE);
				} else {
					new ShowTipDialog().showBuyInfo(SsqxhlbActivity.this, balanceNotFull, "购买失败", buy_icon, dyn[0]);
				}

			} else {
				buy_icon = R.drawable.buy_success;

				String msg = "";

				if ("-1".equals(issueName)) {
					msg = "发起双色球" + " 购买方案\n\n我的认购：" + (allMoney * bs/*
																	 * -
																	 * canDeductMoney
																	 */) + /*"彩豆\n账户余额："
							+ ConvertJsonToList.getMap(js.getString("Data")).get("Balance").toString() + /*
																										 * getBalance
																										 * (
																										 * )
																										 * +
																										 */"彩豆"+"\n方案编号："+js.getString("Data").toString();
				} else {

					msg = "发起双色球" + issueName + "期购买方案\n\n我的认购：" + (allMoney * bs /*
																				 * -
																				 * canDeductMoney
																				 */) + /*"彩豆\n账户余额："
							+ ConvertJsonToList.getMap(js.getString("Data")).get("Balance").toString() + /*
																										 * getBalance
																										 * (
																										 * )
																										 * +
																										 */"彩豆"+"\n方案编号："+js.getString("Data").toString();
				}

				if (!isFinishing()) {
					new ShowTipDialog().showBuyInfo(SsqxhlbActivity.this, msg, "投注成功", buy_icon, dyn[0]);
					clearPUtil();
				}

				// 存贮数据
				MyPreference.getInstance(this).storeBLotID(LotConstants.LOT_ID_SSQ);

			}
		} catch (JSONException ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
		}
	}

	public void Buy2(String strResult) {

		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			if (Integer.parseInt(js.getString("Code")) < 0) {
				buy_icon = R.drawable.buy_failure;
				String balanceNotFull = js.getString("Data");
				// String balance = "当前余额:"+
				// ApplicationData.getInstance().getUserMoney() +"彩豆" +"\n";

				JSONObject params = new JSONObject();
				params.put("Multiple", bs);
				params.put("LotteryID", lotID);
				params.put("IssueName", issueName);
				params.put("Money", bs * allMoney * zh);

				/*if(js.getString("Data").contains(Constants.BALANCE_BUZU)) {
					Intent intent = new Intent();
					intent.setClass(context, JddRechargeListActivity.class);
					intent.putExtra("params", params.toString());
					startActivityForResult(intent, REQ_CODE_NO_MONEY_2_RECHARGE);
				} else {
				new ShowTipDialog().showBuyInfo(SsqxhlbActivity.this, balanceNotFull, "购买失败", buy_icon,
						params.toString());
				}*/
				new ShowTipDialog().showBuyInfoZH(SsqxhlbActivity.this, balanceNotFull, "购买失败", buy_icon,
						params.toString());

			} else {
				buy_icon = R.drawable.buy_success;

				String msg = "";

				msg = "成功连续追号" + zh + "期\n\n我的认购：" + (allMoney * bs * zh) + "彩豆\n账户余额：" + js.getString("Msg").toString()
						+ "彩豆";

				if (!isFinishing()) {
					new ShowTipDialog().showBuyInfoZH(SsqxhlbActivity.this, msg, "追号成功", buy_icon, dyn[0]);
					clearPUtil();
				}
				// 存贮数据
				MyPreference.getInstance(this).storeBLotID(LotConstants.LOT_ID_SSQ);
			}
		} catch (JSONException ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
		}
	}

	public String getBalance() {
		String money = "";
		String strResult = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 设置请求所需参数
			JSONObject params = new JSONObject();
			// 设置请求action
			String action = "107";// 108获取用户基本信息
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params.toString(), UserID, action,
					getApplicationContext());
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			map = ConvertJsonToList.getMap(js.getString("Data"));
			// money =
			// Float.parseFloat(map.get("Balance").toString().replaceAll(",",
			// "").trim());
			money = map.get("Balance").toString();
		} catch (Exception ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		return money;
	}

	public void initView() {
		ceshi = (LinearLayout) findViewById(R.id.regist);
		buy_ssqxhlb_linearlayout01 = findViewById(R.id.buy_ssqxhlb_linearlayout01);
		buy_ssqxhlb_linearlayout02 = findViewById(R.id.buy_ssqxhlb_linearlayout02);
		buy_ssqxhlb_ll01 = (LinearLayout) findViewById(R.id.buy_ssqxhlb_ll01);
		buy_ssqxhlb_ll02 = (LinearLayout) findViewById(R.id.buy_ssqxhlb_ll02);
		// buy_ssqxhlb_Button03 = (Button)
		// findViewById(R.id.buy_ssqxhlb_Button03);
		// buy_ssqxhlb_Button04 = (Button)
		// findViewById(R.id.buy_ssqxhlb_Button04);
		buy_ssqxhlb_ll03 = (LinearLayout) findViewById(R.id.buy_ssqxhlb_ll03);
		buy_ssqxhlb_Button06 = (Button) findViewById(R.id.buy_ssqxhlb_Button06);
		buy_ssqxhlb_btn_hemai = (Button) findViewById(R.id.buy_ssqxhlb_btn_hemai);
		LinearLayout showOrHideLayout = (LinearLayout) findViewById(R.id.ll_show_hide);
//		// IssueID 幸运选号 ""
//		int isFromLucky = getIntent().getIntExtra("isfromlucky", 0);
//		if (isFromLucky == 1) {
//			buy_ssqxhlb_btn_hemai.setVisibility(View.GONE);
//			showOrHideLayout.setVisibility(View.GONE);
//			findViewById(R.id.rlzhuihao).setVisibility(View.INVISIBLE);
//		} else {
//			buy_ssqxhlb_btn_hemai.setVisibility(View.VISIBLE);
//			showOrHideLayout.setVisibility(View.VISIBLE);
//			// findViewById(R.id.rlzhuihao).setVisibility(View.VISIBLE);
//			findViewById(R.id.rlzhuihao).setVisibility(View.VISIBLE);
//		}

		// buy_ssqxhlb_TextView01 = (TextView)
		// findViewById(R.id.buy_ssqxhlb_TextView01);
		// buy_ssqxhlb_TextView02 = (TextView)
		// findViewById(R.id.buy_ssqxhlb_TextView02);
		// buy_ssqxhlb_TextView02.setText("1");
		buy_ssqxhlb_TextView03 = (TextView) findViewById(R.id.buy_ssqxhlb_TextView03);
		buy_ssqxhlb_EditText1 = (EditText) findViewById(R.id.buy_ssqxhlb_EditText01);
		buy_ssqxhlb_EditText1.setText(bs + "");
		// 标题
		titleBar();

		// 软件盘
		ceshi.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

			@Override
			public void onGlobalLayout() {
				int heightDiff = ceshi.getRootView().getHeight() - ceshi.getHeight();
				// 判断焦点在哪里
				if (zhuihao_EditText.hasFocus()) {
					if (heightDiff > 100) {
						// 大小超过100时，一般为显示虚拟键盘事件
						yincangyu1 = (LinearLayout) findViewById(R.id.yincangyu1);
						yincangyu2 = (LinearLayout) findViewById(R.id.yicangyu2);
						yincangyu2.setVisibility(View.VISIBLE);
						wuqi = (TextView) findViewById(R.id.wuqi);
						shiqi = (TextView) findViewById(R.id.shiqi);
						shiwuqi = (TextView) findViewById(R.id.shiwuqi);
						wuqi.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								zh = 5;
								zhuihao_EditText.setText("5");
							}
						});
						shiqi.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								zh = 10;
								zhuihao_EditText.setText("10");
							}
						});
						shiwuqi.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								zh = 15;
								zhuihao_EditText.setText("15");
							}
						});
						if (zh > 1) {
							yincangyu1.setVisibility(View.VISIBLE);
						} else {
							yincangyu1.setVisibility(View.GONE);
						}
					} else {
						yincangyu1 = (LinearLayout) findViewById(R.id.yincangyu1);
						yincangyu2 = (LinearLayout) findViewById(R.id.yicangyu2);
						yincangyu1.setVisibility(View.GONE);
						yincangyu2.setVisibility(View.GONE);
					}
				}

			}
		});
		iszhuihao = (CheckBox) findViewById(R.id.idzhuihao);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void InitBaseAdapter(ArrayList list) {
		// DelButtonAdapter listAdapter = new DelButtonAdapter(this, list,
		// R.layout.buy_ssqxhlb_list, new String[] {
		// "buy_ssqxhlb_list_ssq_redball", "buy_ssqxhlb_list_ssq_blueball",
		// "buy_ssqxhlb_list_ssq_money", "buy_ssqxhlb_list_ssq_delete" }, new
		// int[] { R.id.buy_ssqxhlb_list_ssq_redball,
		// R.id.buy_ssqxhlb_list_ssq_blueball, R.id.buy_ssqxhlb_list_ssq_money,
		// R.id.buy_ssqxhlb_list_ssq_delete });

		NewDelButtonAdapter listAdapter = new NewDelButtonAdapter(
				this,
				list,
				R.layout.buy_ssqxhlb_newlist,
				new String[] { "buy_ssqxhlb_list_ssq_redball", "buy_ssqxhlb_list_ssq_blueball",
						"buy_ssqxhlb_list_ssq_money", "buy_ssqxhlb_list_ssq_delete", "buy_ssqxhlb_list_ssq_playtype" },
				new int[] { R.id.buy_ssqxhlb_list_ssq_redball, R.id.buy_ssqxhlb_list_ssq_blueball,
						R.id.buy_newssq_list_zhumoney, R.id.buy_ssqxhlb_list_ssq_delete, R.id.buy_newssq_list_playtype });
		// 获取目前列表有多少注的记录
		// System.out.println("-------" + listAdapter.GetSsqList().size());
		if (listAdapter.GetSsqList().size() > 0) {
			list = new ArrayList<HashMap<String, Object>>();
			money_dintInt = new DynArrayInt();
			Iterator<BallDTO> it = ApplicationData.getInstance().getList_ssqdto().iterator();
			for (; it.hasNext();) {
				it.next();
				it.remove();
			}
			for (BallDTO ssqdto : listAdapter.GetSsqList()) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				String[] ballString = ssqdto.getSsq_ball().toString().split("-");
				map.put("buy_ssqxhlb_list_ssq_redball", ballString[0].toString().replace(",", " "));
				map.put("buy_ssqxhlb_list_ssq_blueball", ballString[1].toString().replace(",", " "));
				map.put("buy_ssqxhlb_list_ssq_money", ballString[2].toString());
				map.put("buy_ssqxhlb_list_ssq_delete", R.color.common_del);
				list.add(map);

				ssqdto = new BallDTO();
				ssqdto.setSsq_ball(ballString[0].toString().replace(",", " ") + "-"
						+ ballString[1].toString().replace(",", " ") + "-" + ballString[2].toString());

				ApplicationData.getInstance().getList_ssqdto().add(ssqdto);

				// 通过传来的单注金额，保存在money_dintInt数组里,计算出总金额
				money_dintInt.addInt(Integer.parseInt(ballString[2]));

			}
			FactoryAllResult();
		} else {
			buy_ssqxhlb_EditText1.setText("1");
			// buy_ssqxhlb_TextView01.setText("0");
			// buy_ssqxhlb_TextView02.setText("1");
			zhuihao_EditText.setText("1");
			allMoney = 0;
			bs = 1;
			zh = 1;
			buy_ssqxhlb_TextView03.setText("0");
			// 获得自定义的应用程序BallDTO,初始化
			ApplicationData.getInstance().initList();
			list = new ArrayList<HashMap<String, Object>>();
			buy_ssqxhlb_linearlayout01.setVisibility(View.GONE);
			buy_ssqxhlb_linearlayout02.setVisibility(View.VISIBLE);
		}
		setListAdapter(listAdapter);
	}

	private ArrayList<HashMap<String, Object>> getData(String ssq_ball) {
		// 拿到新的号码放到List
		if (!ssq_ball.equals("")) {
			String[] ballString = ssq_ball.split("-");
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("buy_ssqxhlb_list_ssq_redball", ballString[0].toString().replace(",", " "));
			map.put("buy_ssqxhlb_list_ssq_blueball", ballString[1].toString().replace(",", " "));
			map.put("buy_ssqxhlb_list_ssq_money", ballString[2].toString());
			map.put("buy_ssqxhlb_list_ssq_delete", R.drawable.default_delbtn02);
			// 玩法
			if (Integer.parseInt(ballString[2].toString()) > 2) {
				map.put("buy_ssqxhlb_list_ssq_playtype", "复式");
			} else {
				map.put("buy_ssqxhlb_list_ssq_playtype", "单式");
			}

			list.add(map);
		}
		return list;
	}

	public int[] RandomGenData(int min, int max, int num, String color) {
		int[] temp;
		Random rndNumber;
		rndNumber = new Random();
		temp = new int[num];
		ArrayList<Integer> a1 = new ArrayList<Integer>();

		for (int i = min; i <= max; i++) {
			a1.add((Integer) i);
		}
		for (int i = 0; i < num; i++) {
			int index = rndNumber.nextInt(max - min + 1 - i);
			Object o = a1.get(index);
			temp[i] = ((Integer) o).intValue();
			a1.remove(index);
		}
		Arrays.sort(temp);
		return temp;
	}

	// 计算注数和金额
	public void FactoryAllResult() {
		// 计算注数和金额
		int money = 0;
		for (int i = 0; i < money_dintInt.getSize(); i++) {
			money = money + money_dintInt.getInt(i);
		}
		allMoney = money;
		// bs = Integer.parseInt(buy_ssqxhlb_EditText1.getText().toString());
		ApplicationData.getInstance().setAll_ssqmoney(allMoney);
		// buy_ssqxhlb_TextView01.setText(money / 2 + "");
		buy_ssqxhlb_TextView03.setText(money * bs * zh + "");
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if (requestCode == REQ_CODE_BUYMAIN || requestCode == REQ_CODE_NO_MONEY_2_RECHARGE) {
				ApplicationData.getInstance().initList();
				setResult(RESULT_OK);
				finish();
			}
		}
	};

	/*
	 * // 计算注数和金额2 public void FactoryAllResult2(ArrayList<HashMap<String,
	 * Object>> mAppList) { LayoutInflater inflater = (LayoutInflater)
	 * this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view =
	 * inflater.inflate(R.layout.buy_ssqxhlb, null);
	 * 
	 * if (mAppList.size() > 0) { System.out.println("2------" +
	 * mAppList.size()); int money = 0; for (int i = 0; i < mAppList.size();
	 * i++) { String[] ballString = mAppList.get(i).toString().split("-"); money
	 * = money + Integer.parseInt(ballString[2]); } ((TextView)
	 * view.findViewById(R.id.buy_ssqxhlb_TextView01)).setText(mAppList.size() +
	 * ""); ((TextView)
	 * view.findViewById(R.id.buy_ssqxhlb_TextView03)).setText(money + ""); }
	 * else { ((TextView)
	 * view.findViewById(R.id.buy_ssqxhlb_TextView01)).setText("1"); ((TextView)
	 * view.findViewById(R.id.buy_ssqxhlb_TextView03)).setText("0"); }
	 * 
	 * }
	 */

	// TitleBar标题栏
	public void titleBar() {
		// Title信息(返回+Title)
		Button back = (Button) findViewById(R.id.top_title_back);
		back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				onKeyDown(KeyEvent.KEYCODE_BACK, null);
			}
		});

		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText("双色球");// R.string.buy_ssq_lb 双色球-普通

		Button refres = (Button) findViewById(R.id.top_title_refres);
		refres.getBackground().setAlpha(255);
		refres.setVisibility(View.INVISIBLE);
		// refres.setBackgroundResource(R.drawable.default_menu);
		// refres.setVisibility(View.VISIBLE);
		refres.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (ApplicationData.getInstance().getList_ssqdto().size() != 0) {
				MyDialog.Builder dialog = new MyDialog.Builder(context);
				dialog.setTitle("退出提示");
				dialog.setMessage("是否清除本次选号?");
				dialog.setPositiveButton("清除", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						clearPUtil();

						// 获得自定义的应用程序BallDTO,初始化
						ApplicationData.getInstance().initList();
						dialog.cancel();
						finish();
					}
				});
				dialog.setNegativeButton("保存", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						clearPUtil();
						int size = ApplicationData.getInstance().getList_ssqdto().size();
						pUtil.putInt("ssq_size", size);
						for (int i = 0; i < size; i++) {
							pUtil.putString("ssq_ball" + i, ApplicationData.getInstance().getList_ssqdto().get(i)
									.getSsq_ball());
						}
						pUtil.putInt("ssq_allMoney", ApplicationData.getInstance().getAll_ssqmoney());

						ApplicationData.getInstance().initList();
						dialog.cancel();
						finish();
						Toast.makeText(context, R.string.design_change_saved, Toast.LENGTH_SHORT).show();
					}
				}).create().show();
			} else {
				// 无对话框退出
				clearPUtil();
				ApplicationData.getInstance().initList();
				finish();
			}
		} else {
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	// 清除保存的号码记录
	public void clearPUtil() {
		int size = pUtil.getInt("ssq_size", 0);
		if (size != 0) {
			for (int i = 0; i < size; i++) {
				pUtil.remove("ssq_ball" + i);
			}
			pUtil.remove("ssq_size");
			pUtil.remove("ssq_allMoney");
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = new Intent();
		intent.putExtra("position", position);
		intent.putExtra("ifbacklist", true);
		intent.setClass(context, SsqxhActivity.class);
		startActivity(intent);
		finish();
		super.onListItemClick(l, v, position, id);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		SysApplication.getInstance().removeActivity(this);
	};
}